package com.sm.li.controller;

import com.sm.li.common.domin.LoginAdmin;
import com.sm.li.common.exception.ApiException;
import com.sm.li.common.http.AxiosResult;
import com.sm.li.common.http.AxiosStatus;
import com.sm.li.components.TokenService;
import com.sm.li.constants.RedisKey;
import com.sm.li.dto.AdminDTO;
import com.sm.li.dto.MenuDTO;
import com.sm.li.entity.Admin;
import com.sm.li.entity.Menu;
import com.sm.li.service.AdminService;
import com.sm.li.service.MenuService;
import com.sm.li.service.RoleService;
import com.sm.li.transfer.MenuTransfer;
import com.sm.li.utils.TreeUtils;
import com.sm.li.utils.UploadService;
import com.wf.captcha.GifCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("common")
public class CommonController {

    @Autowired
    private UploadService uploadService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private MenuTransfer menuTransfer;

    @Autowired
    private TokenService tokenService;
    //文件上传
    @PostMapping("upload")
    public AxiosResult<String> upload(@RequestPart Part avatar) throws Exception {
        return AxiosResult.success(uploadService.upload(avatar));
    }

    @GetMapping("getCode/{uuid}")
    public AxiosResult<String> getCode(@PathVariable String uuid) {
        // 使用gif验证码
        GifCaptcha gifCaptcha = new GifCaptcha(130, 48, 6);
        //图片中文字的值
        String text = gifCaptcha.text();
        stringRedisTemplate.opsForValue().set(RedisKey.CODE_KEY + uuid, text);
        String s = gifCaptcha.toBase64();
        return AxiosResult.success(s);
    }

    @PostMapping("doLogin")
    public AxiosResult<String> doLogin(@RequestBody Map<String, String> map) {
        String code = map.get("code");
        String uuid = map.get("uuid");
        String username = map.get("username");
        String password = map.get("password");
        String value = stringRedisTemplate.opsForValue().get(RedisKey.CODE_KEY + uuid);
        //判断验证码是否准确
        if (StringUtils.isEmpty(value) || !value.equalsIgnoreCase(code))
            throw new ApiException(AxiosStatus.ERROR);

        Admin admin = adminService.getAdminByAccount(username);
        //账户名称不正确
        if (admin == null)
            throw new ApiException(AxiosStatus.ERROR);

        //比较密码
        //密码错误
        if (!password.equals(admin.getAdminPassword()))
            throw new ApiException(AxiosStatus.ERROR);

        //清除Redis中的验证码数据
        stringRedisTemplate.delete(RedisKey.CODE_KEY + uuid);

        String token = tokenService.createTokenAndCacheLoginAdmin(admin);
        return AxiosResult.success(token);
    }



    @GetMapping("getUserInfo")
    public AxiosResult<Map<String,Object>> getUserInfo(HttpServletRequest httpServletRequest) {

        LoginAdmin loginAdminCache = tokenService.getLoginAdminCache();
        Admin admin = loginAdminCache.getAdmin();

        Map<String,Object> map=new HashMap<>();
        map.put("admin",admin);
        //超级管理员
        if (admin.getIsSuperAdmin()) {
            //获得所有权限
            List<Menu> list = menuService.list();
            //将用户所有权限放在LoginAdmin
            loginAdminCache.setMenus(list);
            List<MenuDTO> menuDTOS = menuTransfer.toDTO(list);
            List<MenuDTO> collect = menuDTOS.stream().filter(menuDTO -> !menuDTO.getMenuType().equals(3)).collect(Collectors.toList());
            List<MenuDTO> btnMenus = menuDTOS.stream().filter(menuDTO -> menuDTO.getMenuType().equals(3)).collect(Collectors.toList());
            List<MenuDTO> root = collect.stream().filter(menuDTO -> menuDTO.getParentId().equals(0L)).collect(Collectors.toList());
            TreeUtils.buildTreeData(root, collect);
            map.put("menuList",root);
            map.put("btnList",btnMenus);
            tokenService.setLoginAdminCache(loginAdminCache);
            return AxiosResult.success(map);

        } else {
            //从用户获得角色
            List<Long> roleIds = adminService.getRolesByAdminId(admin.getId());
            //从角色获得权限
            List<MenuDTO> list = roleService.getMenusByRoleIds(roleIds);
            List<Menu> menus = menuTransfer.toEntity(list);
            loginAdminCache.setMenus(menus);
            //过滤按钮级别
            List<MenuDTO> collect = list.stream().filter(menuDTO -> !menuDTO.getMenuType().equals(3)).collect(Collectors.toList());
            List<MenuDTO> btnMenus = list.stream().filter(menuDTO -> menuDTO.getMenuType().equals(3)).collect(Collectors.toList());
            List<MenuDTO> root = collect.stream().filter(menuDTO -> menuDTO.getParentId().equals(0L)).collect(Collectors.toList());
            TreeUtils.buildTreeData(root, collect);
            map.put("menuList",root);
            map.put("btnList",btnMenus);
            tokenService.setLoginAdminCache(loginAdminCache);
            return AxiosResult.success(map);
        }
    }

@GetMapping("loginStatus")
    public String loginStatus(HttpSession httpSession){
    System.out.println(httpSession);
    return "success";
}
}
